package com.ybkj.daijia.server.controller;

import com.ybkj.daijia.common.Principal;
import com.ybkj.daijia.common.Result;
import com.ybkj.daijia.config.ZhuanxianApi;
import com.ybkj.daijia.server.exception.NoPermissionException;
import com.ybkj.daijia.page.Page;
import com.ybkj.daijia.server.event.model.OperationLogEvent;
import com.ybkj.daijia.server.model.Admin;
import com.ybkj.daijia.server.model.Role;
import com.ybkj.daijia.server.service.AdminService;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.RoleService;
import com.ybkj.daijia.server.service.ZhuanxianService;
import com.ybkj.daijia.server.zhuanxian.Line;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpSession;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author Shine
 */
@Controller
@RequestMapping(value = "role")
public class RoleController {

    @Autowired
    private RoleService roleService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private AdminService adminService;
    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;
    @Autowired
    private ZhuanxianService zhuanxianService;
    @Autowired
    private ZhuanxianApi zhuanxianApi;


    @RequestMapping(value = "list", method = RequestMethod.GET)
    public ModelAndView list(@RequestParam(required = false, value = "name") String name) {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("role")) {
            ModelAndView mv = new ModelAndView();
            mv.setViewName("role/list");

            Subject currentUser = SecurityUtils.getSubject();
            Principal principal = (Principal) currentUser.getPrincipal();
            Page<Role> page = null;
            //主公司
            if (principal.isCompanyType()) {
                page = roleService.queryAll(null, name);
            } else {
                page = roleService.queryAll(principal.getCompanyId(), name);
            }
            mv.addObject("mainCompany", principal.isCompanyType());

            mv.addObject("page", page);
            mv.addObject("name", name);

            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "add", method = RequestMethod.GET)
    public ModelAndView add() {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();
        Long companyId = principal.getCompanyId();
        List<Line> lineList = new ArrayList<>();
        if (subject.isPermitted("role")) {
            ModelAndView mv = new ModelAndView();
            if (null != companyId) {
                lineList = zhuanxianService.queryLines(companyId);
//				lineList = zhuanxianApi.deleteRepeatLine(lineList);
            }
            mv.setViewName("role/add");
            mv.addObject("lineList", lineList);
            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "create", method = RequestMethod.POST)
    public String create(Role role, HttpSession session) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        if (subject.isPermitted("role")) {
            role.setIsInternal(false);
            if (null != principal) {
                role.setCompanyId(principal.getCompanyId());
                role.setCompanyName(principal.getCompanyName());
            }
            roleService.insertRole(role);

            String detail = "【%s】新增了角色【" + role.getName() + "】";
            OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
            applicationEventMulticaster.multicastEvent(operationLogEvent);

            return "redirect:list";
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "edit/{id}", method = RequestMethod.GET)
    public ModelAndView edit(@PathVariable("id") Long id) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();
        Long companyId = principal.getCompanyId();
        List<Line> lineList = new ArrayList<>();
        if (subject.isPermitted("role")) {
            ModelAndView mv = new ModelAndView();
            //主公司
            if (principal.isCompanyType()) {
                lineList = zhuanxianService.queryLines(null);
            } else {
                if (null != companyId) {
                    lineList = zhuanxianService.queryLines(companyId);
//				lineList = zhuanxianApi.deleteRepeatLine(lineList);
                }
            }

            mv.addObject("lineList", lineList);
            Role local = roleService.findOneWithPerms(id);

            mv.addObject("role", local);

            mv.setViewName("role/edit");

            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "update", method = RequestMethod.POST)
    public String update(Role role, Model model) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        if (subject.isPermitted("role")) {
            Role local = roleService.findOne(role.getId());

            boolean isShine = false;
            Admin loginAdmin = adminService.findOne(principal.getId());
            if (loginAdmin.getUsername().equals("shine")) {
                isShine = true;
            }

            if (!isShine && local.getIsInternal()) {
                model.addAttribute("message", "系统内置，不允许修改");
                model.addAttribute("role", local);
                return "role/edit";
            }

            role.setIsInternal(local.getIsInternal());

            roleService.updateByPrimaryKey(role);

            String detail = "【%s】修改了角色【" + role.getName() + "】";
            OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
            applicationEventMulticaster.multicastEvent(operationLogEvent);

            return "redirect:list";
        } else {
            throw new NoPermissionException();
        }

    }


    @RequestMapping(value = "delete", method = RequestMethod.POST)
    public @ResponseBody
    Result<Integer> delete(Long id) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        if (subject.isPermitted("role")) {
            Result<Integer> result = new Result<Integer>();
            Role role = roleService.findOne(id);

            if (role.getIsInternal()) {
                result.setSuccess(false);
                result.setMessage("'" + role.getName() + "'为系统内置，不能删除");
                return result;
            }

            String detail = "【%s】删除了角色【" + role.getName() + "】";

            roleService.delete(role);

            OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
            applicationEventMulticaster.multicastEvent(operationLogEvent);

            result.setSuccess(true);

            return result;
        } else {
            throw new NoPermissionException();
        }

    }

    @org.springframework.web.bind.annotation.InitBinder
    public void InitBinder(WebDataBinder dataBinder) {

        SimpleDateFormat dateFormat = com.ybkj.daijia.constant.DateConstant.DATE_TIME;
        dateFormat.setLenient(false);
        dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));

    }
}

